﻿using E_GovernmentSystem.Models;
using Microsoft.AspNetCore.Mvc;

namespace E_GovernmentSystem.Controllers
{
    /// <summary>
    /// 部门管理
    /// </summary>
    public class DepartMentController : Controller
    {
        /// <summary>
        /// 配置上下文类
        /// </summary>
        private readonly SqlSugar.ISqlSugarClient db;
        public DepartMentController(SqlSugar.ISqlSugarClient _db)
        {
            this.db = _db;
        }
        //部门管理主页面
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 添加/编辑
        /// </summary>
        /// <param name="department"></param>
        /// <returns></returns>
        public IActionResult Save(department department)
        {
            department.CreationTime = DateTime.Now.TimeOfDay.ToString();
            bool res = (db.Storageable(department).DefaultAddElseUpdate().ExecuteCommand()) > 0 ? true : false;

            return Json(res);
        }

        /// <summary>
        /// 单删/批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public IActionResult Delete(string ids)
        {
            bool res = false;
            if (!string.IsNullOrEmpty(ids))
            {
                //判断ids是否包含逗号
                if (ids.Contains(','))
                {
                    string[] idArr = ids.Split(',');
                    int[] intArr = Array.ConvertAll(idArr, int.Parse);
                    res = db.Deleteable<department>().In(intArr).ExecuteCommand() > 0;
                }
                else
                {
                    int id = int.Parse(ids);
                    res = db.Deleteable<department>().In(id).ExecuteCommand() > 0;
                }
            }
            return Json(res);
        }

        /// <summary>
        /// 查询表格数据，用于表格展示/分页
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="strName"></param>
        /// <returns></returns>
        public IActionResult getDepartInfo(int page, int limit, string strName)
        {
            int total = 0;
            List<department> list = db.Queryable<department>()
                .Where(x => (string.IsNullOrEmpty(strName) || x.DepartmentName.Contains(strName)))
                .OrderByDescending(x => x.DepartmentId)
                .ToPageList(page, limit, ref total);

            var json = new
            {
                code = 0,
                data = list,
                count = total,
                msg = ""
            };
            return Json(json);
        }
    }
}
